package com.hspedu.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author 谷其昊
 * @version 1.0
 * @date 2022/3/23
 * @time 17:24
 */
public class ReflectionCreateInstance {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Class userClass = Class.forName("com.hspedu.reflection.User");
        //newInstance方法就是调用无参构造器创建实例
        User user = (User) userClass.newInstance();
        System.out.println(user);
        //获取public的有参构造
        Constructor constructor = userClass.getConstructor(String.class);
        User user1 = (User) constructor.newInstance("hsp");
        System.out.println(user1);

        //获取私有有参构造器
        Constructor constructor1 = userClass.getDeclaredConstructor(int.class, String.class);
        //反射暴破（暴力破解），使用反射访问私有方法或者属性
        constructor1.setAccessible(true);
        User user3 = (User) constructor1.newInstance(20, "gqh");
        System.out.println(user3);
    }
}

class User { //User类
    private int age = 10;
    private String name = "韩顺平教育";

    public User() {//无参 public
    }

    public User(String name) {//public的有参构造器
        this.name = name;
    }

    private User(int age, String name) {//private 有参构造器
        this.age = age;
        this.name = name;
    }

    @Override
    public String toString() {
        return "User [age=" + age + ", name=" + name + "]";
    }
}